<template>
  <div class="box">

    <!-- table -->
    <div class="page-list">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选 <span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }} 数据
        </p>
        <div class="list-top-box-right">
          <el-button type="primary" :disabled="multipleSelection.length != 1" @click="editFunc"
            v-if="$isPer(permission, ['projectField_add'])">字段权限配置</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="tableLoading">
        <el-table ref="table" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" highlight-selection-row border
          @selection-change="handleSelectionChange" @row-click="handleHighlightChangeTable" :header-cell-class-name="hideAllCheckbox" height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column min-width="180px" prop="id" label="编号" show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="180px" prop="name" label="职位名称" show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="180px" prop="updated_at" label="更新时间" show-overflow-tooltip>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加 -->
    <el-dialog :modal-append-to-body="false" :title="`${roleInfoform.name} - 配置字段权限`" :close-on-click-modal="false"
      :visible.sync="dialogVisible" width="990px" :before-close="handleClose">
      <el-tabs v-model="activeName">
        <el-tab-pane :label="item_1.name" :name="`${key_1}`" v-for="(item_1, key_1) in roleInfoform.field_data"
          :key="key_1">
          <div class="tag-box">
            <div class="tag" :class="activeTag == key_2 ? 'active' : ''" v-for="(item_2, key_2) in item_1.children"
              :key="key_2" @click="tagClick(key_2)">{{ item_2.name }}</div>
          </div>
          <div class="permission-list">
            <el-checkbox-group v-model="roleInfoform.checkedList">
              <div class="item-tr">
                <div class="item1-td">
                  <div class="item2-td-name">
                    {{ roleInfoform.field_data[activeName].children[activeTag].name }}
                  </div>
                </div>
                <div class="item2-td">
                  <div class="item2-tr"
                    v-for="(item_3, key_3) in roleInfoform.field_data[activeName].children[activeTag].children"
                    :key="key_3">
                    <div class="item2-td-main">
                      <el-tooltip class="item" effect="dark" :content="item_3.name" placement="right">
                        <div class="item2-td-name">
                          <el-checkbox :label="item_3.field_name" @change="checkAll($event, key_3)">{{ item_3.name
                            }}</el-checkbox>
                        </div>
                      </el-tooltip>
                    </div>
                    <div class="item3-td">
                      <template v-for="(item_4, key_4) in item_3.field_list">
                        <div class="item-fun" :key="key_4">
                          <el-checkbox :label="item_4.field_name" @change="fieldChange($event, key_3, key_4)">{{
                            item_4.name
                          }}</el-checkbox>
                        </div>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </el-tab-pane>
      </el-tabs>


      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="submitFunc" :loading="roleInfoform.submitBtn">修 改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import adminApi from '@/api/adminApi'
// import { permission_field } from './dataNew.js'
import { field_data } from './data.js'
import { permission_field } from './fieldData.js'

export default {
  name: "projectField",
  data() {
    return {
      tableLoading: false,//列表loading
      tableData: [],//列表数据
      multipleSelection: [],//多选数据
      // 弹窗
      dialogVisible: false,
      roleInfoform: {
        name: '',
        checkedList: [],
        field_data: [],
        submitBtn: false,
      },
      permission: [],//操作权限

      activeName: '0',
      activeTag: 0,
    };
  },
  watch: {
    activeName() {
      this.activeTag = 0
    }
  },
  computed: {
  },
  activated() {
  },
  destroyed() {
    window.onresize = null;
  },
  mounted() {
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.getList();
    this.permissionFieldFunc();
  },
  methods: {
    hideAllCheckbox({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) return "setDisable";
    },
    // 字段权限字段数据重组
    permissionFieldFunc() {
      this.roleInfoform.checkedList = []
      this.roleInfoform.field_data = JSON.parse(JSON.stringify(field_data));
      this.activeName = '0'
      this.activeTag = 0
    },
    editFunc() {
      let item = this.multipleSelection[0];
      this.handleEdit(item)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // 单选
      if (val.length > 1 ) {
          this.$refs.table.clearSelection();
          this.$refs.table.toggleRowSelection(val.pop());
      }
    },
    handleHighlightChangeTable(row) {
      if (this.multipleSelection[0] == row) {
          // 取消
          this.multipleSelection = [];
          this.$refs.table.clearSelection();
        } else {
          // 选择
          this.multipleSelection = [row];
          this.$refs.table.clearSelection();
          this.$refs.table.toggleRowSelection(row, true);
        }    
    },
    /************弹窗操作************/
    // tag切换
    tagClick(key) {
      if (this.activeTag == key) return
      this.activeTag = key
    },
    // 关闭添加弹窗
    handleClose() {
      this.permissionFieldFunc();
      this.dialogVisible = false;
    },
    // 修改
    handleEdit(data) {
      console.log(data, 'handleEdit')
      this.roleInfoform.id = data.id;
      this.roleInfoform.name = data.name;
      if (data.field_permissions) {
        let _data = JSON.parse(data.field_permissions);
        console.log(_data, '旧的内容')
        let fieldData = this.roleInfoform.field_data
        fieldData.map(item1 => {
          item1.children.map(item2 => {
            item2.children.map(item3 => {
              if (_data.checkedList.includes(item3.field_name)) {
                item3.state = true
              }
              item3.field_list.map(item4 => {
                if (_data.checkedList.includes(item4.field_name)) {
                  item4.state = true
                }
              })
            })
          })
        })
        console.log(fieldData)
        this.roleInfoform.checkedList = _data.checkedList
        this.roleInfoform.field_data = fieldData
      }
      this.dialogVisible = true;
    },

    fieldChange(state, idx3, idx4) {
      console.log(state, '单选')
      let idx = this.activeName
      let idx2 = this.activeTag
      let list3 = this.roleInfoform.field_data[idx].children[idx2]

      list3.children[idx3].field_list[idx4].state = state
      // 判断是否已全选
      let allNum = 0;
      list3.children[idx3].field_list.forEach(item => {
        if (item.state) {
          allNum += 1
        }
      })
      let id = list3.children[idx3].field_name
      // if (allNum === list3.children[idx3].field_list.length) {
      //   if (!this.roleInfoform.checkedList.includes(id)) {
      //     this.roleInfoform.checkedList.push(id)
      //   }
      // } else {
      //   if (this.roleInfoform.checkedList.includes(id)) {
      //     var index = this.roleInfoform.checkedList.indexOf(id);
      //     this.roleInfoform.checkedList.splice(index, 1);
      //   }
      // }
      if (allNum == 0) {
        list3.children[idx3].state = false
        if (this.roleInfoform.checkedList.includes(id)) {
          var index = this.roleInfoform.checkedList.indexOf(id);
          this.roleInfoform.checkedList.splice(index, 1);
        }
      } else {
        list3.children[idx3].state = true
        if (!this.roleInfoform.checkedList.includes(id)) {
          this.roleInfoform.checkedList.push(id)
        }
      }
    },
    checkAll(state, idx3) {
      console.log(state, "全选")
      let idx = this.activeName
      let idx2 = this.activeTag
      let list3 = this.roleInfoform.field_data[idx].children[idx2]
      let checkedList = this.roleInfoform.checkedList;
      if (state) {
        list3.children[idx3].state = true

        list3.children[idx3].field_list.forEach(item => {
          let id = item.field_name;
          if (!checkedList.includes(id)) {
            item.state = true;
            checkedList.push(id);
          }
        });
      } else {
        list3.children[idx3].state = false

        list3.children[idx3].field_list.forEach(item => {
          let id = item.field_name;
          if (checkedList.includes(id)) {
            var index = checkedList.indexOf(id);
            item.state = false;
            checkedList.splice(index, 1);
          }
        });
      }
    },
    // 修改
    submitFunc() {
      let roleInfoform = this.roleInfoform;
      if (roleInfoform.checkedList.length < 1) {
        this.$message({
          message: "请选择至少一个权限",
          type: "warning",
        });
        return;
      }
      this.roleInfoform.submitBtn = true;

      adminApi.updOrganization({
        id: roleInfoform.id,
        field_permissions: JSON.stringify({
          field_data: roleInfoform.field_data,
          checkedList: roleInfoform.checkedList
        }),//JSON.stringify(field_permissions)
      }).then(res => {
        if (res.code == 200) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.roleInfoform.submitBtn = false;
          this.handleClose();
          this.getList();
        }
      })
    },

    /************end************/
    // 获取列表
    getList() {
      this.tableLoading = true;
      adminApi.getOrganizationList({
        type: 0,
        field_permissions: 1,
        is_enterprise_personnel: 1
      }).then(res => {
        console.log(res, "获取列表数据")
        this.tableLoading = false;
        if (res.code == 200) {
          this.tableData = res.data;
        }
      }).catch(err => {
        this.tableLoading = false;
      })
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .setDisable {
  .cell {
    visibility: hidden;
  }
}
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>